import { regionData, type DataItem } from "element-china-area-data";
import { ref, computed } from "vue";

export default function useCity() {
  const cityPicker = ref();

  const address = ref("");
  const city = ref<Record<string, DataItem[]>>({
    provinces: [],
    citys: [],
    areas: []
  });

  const onInit = () => {
    const provinces = regionData;
    const citys = provinces[0]?.children || [];
    const areas = citys[0]?.children || [];

    city.value = {
      provinces,
      citys,
      areas
    };
  };

  const onConfirm = (e: any) => {
    address.value = e.value.map(item => item.label).join();
    cityPicker.value.close();
  };

  const onChange = (e: any) => {
    const { columnIndex, index, indexs } = e;
    // 改变了省
    if (columnIndex === 0) {
      city.value.citys = city.value.provinces[index]?.children || [];
      city.value.areas = city.value.citys[0]?.children || [];
      cityPicker.value.setIndexs([index, 0, 0], true);
    } else if (columnIndex === 1) {
      city.value.areas = city.value.citys[index]?.children || [];
      cityPicker.value.setIndexs(indexs, true);
    }
  };

  const open = (provinceName: string, cityName: string, areaName: string) => {
    (provinceName = provinceName || "北京市"),
      (cityName = cityName || "市辖区");
    areaName = areaName || "东城区";
    const provinces = city.value.provinces as DataItem[];
    const p = provinces.findIndex(
      (item: DataItem) => item.label === provinceName
    );
    const citys = provinces[p]?.children || [];
    const c = citys.findIndex((item: DataItem) => item.label === cityName);

    const areas = citys[c]?.children || [];
    const a = areas.findIndex((item: DataItem) => item.label === areaName);

    console.log("provinceName", provinceName);
    city.value.citys = citys;
    city.value.areas = areas;
    cityPicker.value.setIndexs([p, c, a], true);
    cityPicker.value.open();
  };

  const columns = computed(() => [
    city.value.provinces,
    city.value.citys,
    city.value.areas
  ]);

  return {
    address,
    columns,
    cityPicker,
    onChange,
    open,
    onInit,
    onConfirm
  };
}
